package cn.zd.demo1;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageButtonActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_loadimgforbtn;
    private ImageButton imageButton1;
    private ImageButton imageButton2;
    private ExecutorService executors;
    private String[] imageUrls = {"https://cdn2.jianshu.io/assets/web/nav-logo-4c7bbafe27adc892f3046e6978459bac.png"
            ,"https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"
            ,"https://pa.master336.cn:4433/pa/static/common/img/logo.png"
            ,"https://img-home.csdnimg.cn/images/20201124032511.png"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Toast.makeText(this,this.getClass().getName(),Toast.LENGTH_LONG).show();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imagebutton);
        tv_loadimgforbtn = findViewById(R.id.tv_loadimgforbtn);
        tv_loadimgforbtn.setOnClickListener(this);
        ImageButton btn = findViewById(R.id.btn);
        btn.setOnClickListener(v -> {
            Toast.makeText(ImageButtonActivity.this,"点我干啥！",Toast.LENGTH_SHORT).show();
        });
        imageButton1 = findViewById(R.id.btn_imgformurl1);
        imageButton2 = findViewById(R.id.btn_imgformurl2);
        executors = Executors.newFixedThreadPool(2);
    }

    @Override
    public void onClick(View v) {
        int indexImg = new Random().nextInt(imageUrls.length);
        // 第一种更新方法
         new LoadImageTaskByAsyncTask().executeOnExecutor( executors,imageUrls[indexImg]);
        // 第二种更新方法
        executors.execute(new LoadImageTaskRunnable(imageUrls[(indexImg+1)%imageUrls.length]));
    }
    private class LoadImageTaskByAsyncTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... urls) {
            String imageUrl = urls[0];
            Bitmap bitmap = null;
            try {
                // 创建 URL 对象
                URL url = new URL(imageUrl);

                // 打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // 设置请求方法
                connection.setRequestMethod("GET");

                // 获取输入流
                InputStream inputStream = connection.getInputStream();

                // 将输入流解码为 Bitmap
                bitmap = BitmapFactory.decodeStream(inputStream);

                // 关闭输入流和连接
                inputStream.close();
                connection.disconnect();

            } catch (IOException e) {
                e.printStackTrace();
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                // 设置图片到 ImageButton
                imageButton1.setImageBitmap(bitmap);
            }
        }
    }
    private class LoadImageTaskRunnable implements Runnable {

        private String imageUrl;

        public LoadImageTaskRunnable(String imageUrl) {
            this.imageUrl = imageUrl;
        }

        @Override
        public void run() {
            Bitmap bitmap = null;
            try {
                // 创建 URL 对象
                URL url = new URL(imageUrl);

                // 打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // 设置请求方法
                connection.setRequestMethod("GET");

                // 获取输入流
                InputStream inputStream = connection.getInputStream();

                // 将输入流解码为 Bitmap
                bitmap = BitmapFactory.decodeStream(inputStream);

                // 关闭输入流和连接
                inputStream.close();
                connection.disconnect();

            } catch (IOException e) {
                e.printStackTrace();
            }

            // 在主线程更新 UI
            final Bitmap finalBitmap = bitmap;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (finalBitmap != null) {
                        // 设置图片到 ImageButton
                        imageButton2.setImageBitmap(finalBitmap);
                    }
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭线程池
        executors.shutdown();
    }
}